<template>
  <div class="fill-height">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <div class="header-content">
        <el-button
          icon
          @click="$router.go(-1)"
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <h1 class="page-title">
          <el-icon class="title-icon"><Document /></el-icon>
          任务执行日志
        </h1>
      </div>
    </div>

    <!-- 任务执行统计图表 -->
    <el-card class="chart-card" header="任务执行统计">
      <template #header>
        <div class="card-header">
          <span>任务执行统计</span>
          <el-space>
            <el-date-picker
              v-model="dailyExecutionDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="loadDailyExecutionData"
            />
            <el-button
              type="primary"
              @click="loadDailyExecutionData"
              :loading="dailyExecutionLoading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </el-space>
        </div>
      </template>

      <el-row :gutter="16" v-if="dailyExecutionData">
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number">{{ dailyExecutionData.totalExecutions }}</div>
            <div class="stat-label">总执行次数</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number success">{{ dailyExecutionData.successCount }}</div>
            <div class="stat-label">成功次数</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number error">{{ dailyExecutionData.failureCount }}</div>
            <div class="stat-label">失败次数</div>
          </div>
        </el-col>
      </el-row>

      <div class="chart-container" v-if="dailyExecutionData">
        <v-chart :option="executionChartOption" style="height: 400px;" />
      </div>
    </el-card>

    <!-- 搜索和过滤区域 -->
    <el-card class="search-card" header="搜索条件">
      <el-row :gutter="16">
        <el-col :span="8">
          <div class="checkbox-group">
            <div class="checkbox-label">触发状态：</div>
            <el-checkbox-group v-model="searchForm.triggerCode" class="checkbox-list">
              <el-checkbox
                v-for="option in triggerCodeOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="searchForm.executorAddress"
            placeholder="执行器地址"
            clearable
          />
        </el-col>
        <el-col :span="8">
          <el-space>
            <el-button
              type="primary"
              @click="loadJobLogs"
              :loading="loading"
            >
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="table-card" header="执行日志">
      <template #header>
        <div class="card-header">
          <span>执行日志</span>
          <el-button
            type="primary"
            @click="refreshList"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table
        :data="jobLogs"
        :loading="loading"
        style="width: 100%"
        row-key="id"
        size="default"
      >
        <el-table-column prop="jobName" label="任务名称" />
        <el-table-column prop="executorAddress" label="执行器地址" />
        <el-table-column prop="executorShardingIndex" label="分片索引" width="100" />
        <el-table-column prop="executorShardingParam" label="分片参数" />
        <el-table-column prop="triggerTime" label="触发时间" />
        <el-table-column prop="startTime" label="实际执行开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="timeCost" label="耗时(ms)" width="100" />
        <el-table-column prop="triggerCode" label="触发状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getTriggerStatusType(row.triggerCode)">
              {{ row.triggerCodeDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggerMsg" label="运行结果" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                size="small"
                @click="viewLogDetail(row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { jobLogApi } from '@/services/api'
import type { JobLogVO, JobLogQueryDTO, JobDailyExecutionVO, ApiResult, PageResult } from '@/types/job'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const dailyExecutionLoading = ref(false)
const jobLogs = ref<JobLogVO[]>([])
const dailyExecutionData = ref<JobDailyExecutionVO | null>(null)
const dailyExecutionDate = ref(new Date().toISOString().split('T')[0])

// 搜索表单
const searchForm = reactive({
  triggerCode: [] as number[],
  executorAddress: ''
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 触发状态选项 - 使用 triggerCode
const triggerCodeOptions = [
  { label: '触发成功', value: 1 },
  { label: '触发失败', value: 0 }
]

// 执行统计图表配置
const executionChartOption = computed(() => {
  if (!dailyExecutionData.value) {
    return {
      title: {
        text: '任务执行统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '执行状态',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 0, name: '成功', itemStyle: { color: '#67c23a' } },
            { value: 0, name: '失败', itemStyle: { color: '#f56c6c' } },
            { value: 0, name: '运行中', itemStyle: { color: '#e6a23c' } }
          ]
        }
      ]
    }
  }

  return {
    title: {
      text: '任务执行统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '执行状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: dailyExecutionData.value.successCount, name: '成功', itemStyle: { color: '#67c23a' } },
          { value: dailyExecutionData.value.failureCount, name: '失败', itemStyle: { color: '#f56c6c' } },
          { value: dailyExecutionData.value.runningCount, name: '运行中', itemStyle: { color: '#e6a23c' } }
        ]
      }
    ]
  }
})

// 获取触发状态类型
const getTriggerStatusType = (code: number) => {
  switch (code) {
    case 1:
      return 'success'
    case 0:
      return 'danger'
    default:
      return 'info'
  }
}

// 加载每日执行统计
const loadDailyExecutionData = async () => {
  const jobId = Number(route.params.id)
  if (!jobId) {
    console.error('任务ID无效')
    return
  }

  dailyExecutionLoading.value = true
  try {
    const response: ApiResult<JobDailyExecutionVO> = await jobLogApi.queryJobDailyExecution({
      jobId: jobId,
      queryDate: dailyExecutionDate.value
    })

    if (response.success) {
      dailyExecutionData.value = response.data
    }
  } catch (error) {
    console.error('加载每日执行统计失败:', error)
  } finally {
    dailyExecutionLoading.value = false
  }
}

// 加载任务日志
const loadJobLogs = async () => {
  const jobId = Number(route.params.id)
  if (!jobId) {
    console.error('任务ID无效')
    return
  }

  loading.value = true
  try {
    const params: JobLogQueryDTO = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      jobId: jobId,
      triggerCode: searchForm.triggerCode.length > 0 ? searchForm.triggerCode[0] : undefined,
      executorAddress: searchForm.executorAddress || undefined
    }

    const response: ApiResult<PageResult<JobLogVO>> = await jobLogApi.queryJobLogPage(params)

    if (response.success) {
      jobLogs.value = response.data.records
      pagination.total = response.data.total
    } else {
      console.error('加载任务日志失败:', response.message)
    }
  } catch (error) {
    console.error('加载任务日志出错:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.triggerCode = []
  searchForm.executorAddress = ''
  pagination.pageNum = 1
  loadJobLogs()
}

// 刷新列表
const refreshList = () => {
  loadJobLogs()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadJobLogs()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  loadJobLogs()
}

// 查看日志详情
const viewLogDetail = (log: JobLogVO) => {
  // 这里可以打开一个对话框显示详细信息
  console.log('查看日志详情:', log)
}

// 组件挂载时加载数据
onMounted(() => {
  loadDailyExecutionData()
  loadJobLogs()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  align-items: center;
}

.back-btn {
  margin-right: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.chart-card {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 0;
  margin-bottom: 16px;
  border: 2px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.error {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-container {
  margin-top: 20px;
}

.search-card {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.fill-height {
  width: 80vw;
  max-width: 1200px;
  margin: 0 auto;
}

/* 现代化表格样式 */
.el-table {
  border: 2px solid #cbd5e1;
  border-radius: 0;
  box-shadow: 0 4px 12px rgba(30, 58, 138, 0.1);
  position: relative;
  overflow: hidden;
}


/* 表头样式 */
.el-table :deep(.el-table__header-wrapper) {
  background: #f1f5f9;
}

.el-table :deep(.el-table__header) {
  background: #f1f5f9;
}

.el-table :deep(.el-table__header th) {
  background: #f1f5f9 !important;
  color: #475569;
  font-weight: 600;
  font-size: 14px;
  padding: 16px 12px;
  border-bottom: 2px solid #cbd5e1;
  border-right: 1px solid #cbd5e1;
  text-align: left;
  position: relative;
}

.el-table :deep(.el-table__header th:last-child) {
  border-right: none;
}

/* 表格内容样式 */
.el-table :deep(.el-table__body-wrapper) {
  background: #ffffff;
}

.el-table :deep(.el-table__body tr) {
  background: #ffffff;
  transition: background-color 0.2s ease;
}

/* 隔行换色 */
.el-table :deep(.el-table__body tr:nth-child(even)) {
  background: #f8f9fa;
}

.el-table :deep(.el-table__body tr:hover) {
  background: #e3f2fd !important;
}

/* 单元格样式 */
.el-table :deep(.el-table__body td) {
  padding: 16px 12px;
  border-bottom: 1px solid #e0e0e0;
  border-right: 1px solid #e0e0e0;
  font-size: 14px;
  color: #2c3e50;
  text-align: left;
  position: relative;
}

.el-table :deep(.el-table__body td:last-child) {
  border-right: none;
}

/* 数字列右对齐 */
.el-table :deep(.el-table__body td[data-numeric="true"]) {
  text-align: right;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-weight: 500;
}

/* 状态标签样式 */
.el-table :deep(.el-tag) {
  border-radius: 0;
  font-weight: 600;
  padding: 4px 8px;
  border: 1px solid;
  position: relative;
}

.el-table :deep(.el-tag--success) {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #2e7d32;
}

.el-table :deep(.el-tag--warning) {
  background: #fff8e1;
  border-color: #ff9800;
  color: #f57c00;
}

.el-table :deep(.el-tag--danger) {
  background: #ffebee;
  border-color: #f44336;
  color: #c62828;
}



/* 关键数据标注 */
.el-table :deep(.el-table__body td[data-key="true"]) {
  position: relative;
}

.el-table :deep(.el-table__body td[data-key="true"]::before) {
  content: '◆';
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  color: #409eff;
  font-size: 12px;
  font-weight: bold;
}

/* 卡片样式优化 */
.el-card {
  border-radius: 0;
  border: 2px solid #e0e0e0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.el-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 2px solid #e0e0e0;
  padding: 16px 20px;
}

.el-card :deep(.el-card__body) {
  padding: 20px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 0;
  font-weight: 600;
  border: 2px solid;
  transition: all 0.2s ease;
}

.el-button--primary {
  background: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background: #337ecc;
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 选择器样式优化 */
.el-select :deep(.el-input__wrapper) {
  border-radius: 0;
  border: 2px solid #e0e0e0;
  box-shadow: none;
}

.el-select :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

/* 日期选择器样式优化 */
.el-date-picker :deep(.el-input__wrapper) {
  border-radius: 0;
  border: 2px solid #e0e0e0;
  box-shadow: none;
}

/* 分页样式优化 */
.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-pagination :deep(.el-pager li) {
  border-radius: 0;
  border: 1px solid #e0e0e0;
  margin: 0 2px;
}

.el-pagination :deep(.el-pager li.is-active) {
  background: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

/* 搜索表单样式优化 */
.search-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}

.search-form :deep(.el-input__wrapper) {
  border-radius: 0;
  border: 2px solid #e0e0e0;
  box-shadow: none;
}

.search-form :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

/* 复选框组样式优化 */
.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkbox-label {
  font-size: 14px;
  color: #2c3e50;
  font-weight: 600;
}

.checkbox-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.checkbox-list :deep(.el-checkbox) {
  margin-right: 0;
}

.checkbox-list :deep(.el-checkbox__input) {
  border-radius: 0;
}

.checkbox-list :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: #409eff;
  border-color: #409eff;
  border-radius: 0;
}
</style>
